<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <!-- 绑定 -->
      <input type="text" v-model="obj.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="obj.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="obj.gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="msg1">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="fn(item.id)">删除</button>
            <button @click="btn(item)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 设置空对象
      obj: {
        id: "",
        name: "",
        age: "",
        gender: "",
      },
      list: [],
    };
  },
  methods: {
    msg1() {
      if (this.obj.id === "") {
        if (this.obj.name === "") return alert("11");
        if (this.obj.age === "") return alert("11");
        if (this.list.length > 0) {
          this.obj.id = this.list[this.list.length - 1].id + 1;
          this.list.push(this.obj);
          this.obj = { id: "", name: "", age: "", gender: "" };
        } else {
          this.obj.id = 1;
          this.list.push(this.obj);
          this.obj = { id: "", name: "", age: "", gender: "" };
        }
      } else {
        const index1 = this.list.findIndex((item) => item.id === this.obj.id);
        this.list[index1] = { ...this.obj };
        this.obj = { id: "", name: "", age: "", gender: "" };
      }
    },
    fn(i) {
      const index = this.list.findIndex((item) => item.id === i);
      this.list.splice(index, 1);
    },
    btn(data) {
      this.obj = { ...data };
    },
  },
};
</script>
